#!/bin/sh /etc/rc.common
# Copyright (C) 2018-2020 Lienol <lawlienol@gmail.com>

START=99

CONFIG=v2ray_server
CONFIG_PATH=/var/etc/$CONFIG
LOG_PATH=/var/log/$CONFIG
LOG_APP_FILE=$LOG_PATH/app.log

echolog() {
	echo -e "$(date "+%Y-%m-%d %H:%M:%S"): $1" >> $LOG_APP_FILE
}

gen_v2ray_config_file() {
	config_get enable $1 enable
	[ "$enable" = "0" ] && return 0
	config_get remarks $1 remarks
	config_get port $1 port
	config_get transport $1 transport
	lua /usr/lib/lua/luci/model/cbi/v2ray_server/api/genv2rayconfig.lua $1 > $CONFIG_PATH/$1.json
	echolog "$remarks $port 生成并运行 V2ray 配置文件 - $CONFIG_PATH/$1.json" 
	/usr/bin/v2ray/v2ray -config $CONFIG_PATH/$1.json >/dev/null 2>&1 &
}

start_v2ray_server() {
	mkdir -p $CONFIG_PATH $LOG_PATH
	touch $LOG_APP_FILE
	config_foreach gen_v2ray_config_file "user"
	fw3 reload > /dev/null 2>&1 &
}

stop_v2ray_server() {
	fw3 reload > /dev/null 2>&1
	ps -w | grep "$CONFIG_PATH/" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	rm -rf $CONFIG_PATH
	rm -rf $LOG_PATH
}

start() {
	config_load $CONFIG
	enable=$(uci get $CONFIG.@global[0].enable)
	if [ "$enable" = "0" ];then
		stop_v2ray_server
	else
		start_v2ray_server
	fi
}

stop() {
	stop_v2ray_server
}

restart() {
	stop
	start
}